package com.orangecy.common.feature;

import com.google.common.collect.Maps;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;

/**
 * @Author : orangeCy.奕
 * @Time : 2021/9/23
 * @desc : 猎豹养成产品源码
 * 对结构化String封装KV操作
 */
public class FeatureStrUtil {
    private static final String ENTRY_SEPARATE = ";";
    private static final String KV_SEPARATE = ":";

    /**
     * 读取feature中key的value
     * @param feature
     * @param key
     * @return
     */
    public static String getFeature(String feature,String key) {
        //将feature转为map结构
        Map<String,String> featureMap = convertMap(feature);
        return featureMap.get(key);
    }

    /**
     * 写入key,value 到feature
     * @param feature
     * @param key
     * @param value
     * @return
     */
    public static String putFeature(String feature,String key,String value) {
        //将feature转为map结构
        Map<String, String> featureMap = convertMap(feature);
        featureMap.put(key,value);
        return convertStr(featureMap);
    }

    /**
     * 将结构化map数据转为feature
     * @param featureMap
     * @return
     */
    private static String convertStr(Map<String, String> featureMap) {
        StringBuilder sb = new StringBuilder(ENTRY_SEPARATE);
        if(MapUtils.isEmpty(featureMap)) {
            return sb.toString();
        }
        for(Map.Entry<String,String> entry : featureMap.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            if(null == k || null == v) {
                continue;
            }
            sb.append(k).append(KV_SEPARATE).append(v).append(ENTRY_SEPARATE);
        }
        return sb.toString();
    }

    /**
     * 将feature转为结构化map数据
     * @param feature
     * @return
     */
    private static Map<String, String> convertMap(String feature) {
        if(StringUtils.isBlank(feature)) {
            return Maps.newHashMap();
        }
        Map<String, String> retMap = Maps.newHashMap();
        String[] splitArr = StringUtils.split(feature,ENTRY_SEPARATE);

        for(String entry : splitArr) {
            if(StringUtils.isBlank(entry)) {
                continue;
            }
            //将entry kv键值对 拆开
            String[] splitKV = StringUtils.split(entry, KV_SEPARATE, 2);
            if(splitKV.length != 2) {
                continue;
            }
            String k = splitKV[0];
            String v = splitKV[1];
            if(StringUtils.isNoneBlank(k) && StringUtils.isNoneBlank(v)) {
                retMap.put(k,v);
            }
        }
        return retMap;
    }

    public static void main(String[] args) {
        String originFeature = "";
        String feature = FeatureStrUtil.putFeature(originFeature, "lb", "nb");
        String value = FeatureStrUtil.getFeature(feature, "lb");
        System.out.println(feature);
        System.out.println(value);
    }
}